﻿using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Linq;

using PetaPoco;

using Happy.Query.PetaPoco.Test.Stub;

namespace Happy.Query.PetaPoco.Test
{
    [TestClass]
    public class PetaPocoQuerySourceTest
    {
        private static readonly string _ConnectionString = @"Data Source=(LocalDB)\v11.0;AttachDbFilename=" + Environment.CurrentDirectory + @"\App_Data\PetaPocoDatabase.mdf;Integrated Security=True;Connect Timeout=30";
        private const string _ProviderName = "System.Data.SqlClient";

        [ClassInitialize]
        public static void Initialize(TestContext context)
        {
            var db = CreateDatabase();

            db.Execute("DELETE FROM Users");
            db.Execute("DELETE FROM Posts");

            for (var i = 1; i <= 10; i++)
            {
                var userId = Guid.NewGuid();
                db.Insert("Users", "Id", false, new
                {
                    Id = userId,
                    Name = "段光伟" + i,
                    Age = 25 + i,
                    IsAdmin = i % 2 == 0
                });

                db.Insert("Posts", "Id", false, new
                {
                    Id = Guid.NewGuid(),
                    Content = "测试" + i,
                    UserId = userId
                });
            }
        }

        [TestMethod]
        public void Page_Test()
        {
            var querySource = new UserQuerySource();
            var query = QueryArgument.Create("Name LIKE @0", new object[] { "段光伟%" });

            var result = querySource.Page(query, 2, 5);

            Assert.AreEqual(2, result.TotalPages);
            Assert.AreEqual(10, result.TotalItems);
            Assert.AreEqual(5, result.Items.Count());
        }

        [TestMethod]
        public void Fetch_Test()
        {
            var querySource = new UserQuerySource();
            var query = QueryArgument.Create("Name LIKE @0", new object[] { "段光伟%" });

            var results = querySource.Fetch(query);

            Assert.AreEqual(10, results.Count());
        }

        [TestMethod]
        public void SingleOrDefault_Test()
        {
            var querySource = new UserQuerySource();
            var query = QueryArgument.Create("Name = @0", new object[] { "段光伟1" });

            var result = querySource.SingleOrDefault(query);

            Assert.IsNotNull(result);
        }

        private static Database CreateDatabase()
        {
            return new Database(_ConnectionString, _ProviderName);
        }
    }
}
